import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import type {ProTableProps} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type {SysRoleData, SysRoleParams, SysRoleAdd} from "@/pages/system/role/type";
import columns from "@/pages/system/role/list/config/columns";
import {Button, message, Space} from "antd";
import React, {useRef, useState} from "react";
import type {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadSysRoleExport,
  downloadSysRoleExportTemplate,
  sysRoleImport,
  sysRoleUpdate,
  sysRoleAdd,
  sysRolePageList,
  sysRoleRemove
} from "@/services/system/role/api";
import {history} from "umi";
import type {OptionActions} from "@/type/type";
import AddSysRole from "@/pages/system/role/list/components/AddSysRole";
import type {ProFormInstance} from "@ant-design/pro-form";

export default () => {

  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number | string)[]>([]);

  const sysRoleAddRef: React.MutableRefObject<ProFormInstance<SysRoleAdd> | undefined> = useRef<ProFormInstance<SysRoleAdd> | undefined>();
  const optionAction: OptionActions<SysRoleAdd, SysRoleData> = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        sysRoleImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(data) {
      // @ts-ignore
      sysRoleUpdate(data).then(res => {
        message.success("编辑成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
        window.location.reload();
      });
    },
    editModal: (data: SysRoleData) => {
      sysRoleAddRef.current?.setFieldsValue(data)
      return {
        trigger: <Button type="link" onClick={() => sysRoleAddRef.current?.setFieldsValue(data)}>编辑</Button>,
        onFinish: async (formData) => {
          await sysRoleAddRef.current?.validateFields().then(res => {
            const sysRole: any = {
              ...formData,
              id: data.id
            }
            sysRoleUpdate(sysRole).then(res => {
              message.success("操作成功")
              sysRoleAddRef.current?.resetFields();
              actionRef.current?.reload();
              window.location.reload();
            })
          })
          return true
        },
        formRef: sysRoleAddRef,
        title: "编辑角色",
        width: 500,
      }
    },
    add() {
      history.push({
        pathname: "sys/role/add"
      })
    },
    addModal: {
      trigger: <Button type="primary" onClick={() => sysRoleAddRef.current?.resetFields()}>新增</Button>,
      onFinish: async (formData) => {
        await sysRoleAddRef.current?.validateFields().then(res => {
          sysRoleAdd(formData as SysRoleAdd).then(res => {
            message.success("新增成功")
            sysRoleAddRef.current?.resetFields();
            actionRef.current?.reload();
          })
        })
        return true
      },
      formRef: sysRoleAddRef,
      title: "新增角色",
      width: 800,
    },
    export() {
      downloadSysRoleExport(selectedRowKeys).then(res => {
        message.success("导出成功").then(res => {
        })
        setSelectedRowKeys([]);

      })
    },
    remove(ids) {
      sysRoleRemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    exportTemplate() {
      downloadSysRoleExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    }
  }

  // @ts-ignore
  const tableProps
    :
    ProTableProps<SysRoleData, SysRoleParams> = {
    rowSelection: {
      // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      // selections: [],
    },
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys);
      return (
        <Space size={24}>
                      <span>
                          已选 {selectedRowKeys.length} 项
                          <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                           取消选择
                         </a>
                      </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove([])}>批量删除</a>
          <a onClick={() => optionAction.export()}>导出数据</a>
        </Space>
      );
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    // @ts-ignore
    columns: columns(optionAction),
    request: async (params, sort, filter) => {
      return await sysRolePageList(params).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        <AddSysRole {...optionAction.addModal}/>
        {/*<Upload {...optionAction.import}>*/}
        {/*  <Button type="primary">导入</Button>*/}
        {/*</Upload>*/}
        {/*<Button type="primary" onClick={() => optionAction.export()}>导出</Button>*/}
        {/*<Button type="primary" onClick={() => optionAction.exportTemplate()}>导出模版</Button>*/}
      </Space>
    ),
    actionRef,
    rowKey: "id"
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<SysRoleData, SysRoleParams> {...tableProps}>
        </ProTable>
      </ProCard>
    </PageContainer>
  )
}
